package com.chrray.position.auth;


import com.alibaba.fastjson.JSONObject;
import com.chrray.position.util.redis.RedisUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;


/**
 * 认证信息上下文
 **/
public class AuthenticationContext implements AutoCloseable {
    public static final String WX_TOKEN_PREFIX = "wx_token:";

    private static ApplicationContext context;
    private static RedisUtils redisUtils;

    static final ThreadLocal<Authentication> ctx = new ThreadLocal<>();

    public static void setupContext(ApplicationContext applicationContext) {
        context = applicationContext;
        redisUtils = context.getBean(RedisUtils.class);
    }


    public static void storeContext(Authentication authentication) {
        RedisUtils redisUtils = context.getBean(RedisUtils.class);
        String ctxStr = JSONObject.toJSONString(authentication);
        ctx.set(authentication);
        redisUtils.setHour(WX_TOKEN_PREFIX+authentication.getToken(),ctxStr,24*7);
    }





    public static Authentication context() {
        return ctx.get();
    }


    public static void refreshContext(Authentication context) {
        ctx.set(context);
        String token = context.getToken();
        String ctxStr = JSONObject.toJSONString(context);
        redisUtils.setHour(WX_TOKEN_PREFIX+token, ctxStr, 24*7);
    }

    public static  boolean restoreContext(String token) {
        String ctxStr = redisUtils.getString(WX_TOKEN_PREFIX+token);
        if(StringUtils.isEmpty(ctxStr)) {
            return false;
        }
        Authentication context = JSONObject.parseObject(ctxStr, Authentication.class);
        AuthenticationContext.context(context);
        return true;
    }

    private static void context(Authentication authentication) {
        ctx.set(authentication);
    }

    public static void clear() {
        ctx.remove();
    }

    @Override
    public void close() throws Exception {
        ctx.remove();
    }
}
